<template>
  <div class="user-profile">
    <!-- <div class="avatar-section">
      <div class="avatar-container">
        <img :src="avatarUrl" alt="用户头像" class="avatar" />
        <button @click="showAvatarModal = true" class="change-avatar-btn">修改头像</button>
      </div>
    </div> -->
    <div class="avatar-section">
      <div class="avatar-container">
        <el-avatar :src="getAvatarUrl(user?.avatar)" style="width: 120px; height: 120px;" />
        <button @click="showAvatarModal = true" class="change-avatar-btn">修改头像</button>
      </div>
    </div>

    <div class="info-section">
      <h2 style="color: #3998a9;">基本设置</h2>

      <div class="info-form">
        <div class="info-item">
          <label>昵称</label>
          <div v-if="!editing" class="info-value">{{ userInfo.nickname }}</div>
          <input v-else v-model="editInfo.nickname" type="text" />
        </div>

        <div class="info-item">
          <label>邮箱</label>
          <div v-if="!editing" class="info-value">{{ userInfo.email }}</div>
          <div v-else>
            <input v-model="editInfo.email" type="email" />
            <span v-if="emailError" class="error-message">{{ emailError }}</span>
          </div>
        </div>

        <div class="info-item">
          <label>电话</label>
          <div v-if="!editing" class="info-value">{{ userInfo.phone || '未填写' }}</div>
          <div v-else>
            <input v-model="editInfo.phone" type="tel" placeholder="请输入手机号码" />
            <span v-if="phoneError" class="error-message">{{ phoneError }}</span>
          </div>
        </div>

        <div class="info-item">
          <label>个人介绍</label>
          <div v-if="!editing" class="info-value">{{ userInfo.description || '请输入个人介绍' }}</div>
          <textarea v-else v-model="editInfo.description"></textarea>
        </div>
        <!-- <div class="info-item">
          <label>居住地</label>
          <div v-if="!editing" class="info-value">{{ userInfo.location }}</div>
          <input v-else v-model="editInfo.location" type="text" />
        </div> -->

        <div class="action-buttons">
          <button v-if="!editing" @click="startEditing" class="edit-btn">编辑信息</button>
          <template v-else>
            <button @click="saveInfo" class="save-btn" :disabled="!isFormValid">保存</button>
            <button @click="cancelEditing" class="cancel-btn">取消</button>
          </template>
        </div>
      </div>
    </div>

    <!-- 修改头像模态框 -->
    <el-dialog v-model="showAvatarModal" title="修改头像" width="700px" :close-on-click-modal="false">
      <div class="avatar-modal-content">
        <div class="avatar-comparison-container">
          <!-- 左侧：当前头像 -->
          <div class="current-avatar-section">
            <h4>当前头像</h4>
            <div class="current-avatar-container">
              <el-avatar :src="getAvatarUrl(user?.avatar)" style="width: 120px; height: 120px;" />
              <p class="avatar-tip">当前使用的头像</p>
            </div>
          </div>

          <!-- 中间：选择按钮 -->
          <div class="select-button-section">
            <div class="file-upload-container">
              <el-upload ref="uploadRef" :auto-upload="false" :show-file-list="false" :on-change="handleAvatarChange"
                accept="image/*" class="avatar-upload">
                <el-button type="primary" icon="Plus">选择图片</el-button>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 JPG、PNG、GIF 格式<br>文件大小不超过 2MB
                  </div>
                </template>
              </el-upload>
            </div>
          </div>

          <!-- 右侧：新头像预览 -->
          <div class="new-avatar-section">
            <h4>新头像</h4>
            <div v-if="newAvatarPreview" class="new-avatar-container">
              <div class="preview-container">
                <el-avatar :src="newAvatarPreview" style="width: 120px; height: 120px;" />
                <p class="preview-tip">新头像效果</p>
              </div>
            </div>
            <div v-else class="placeholder-container">
              <div class="placeholder-content">
                <el-icon style="font-size: 48px; color: #c0c4cc;">
                  <User />
                </el-icon>
                <p class="placeholder-tip">请选择新头像</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAvatarChange">取消</el-button>
          <el-button type="primary" @click="handleUploadAvatar" :disabled="!newAvatar" :loading="uploading">
            {{ uploading ? '上传中...' : '上传头像' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 操作成功提示 -->
    <div v-if="showSuccessMessage" class="success-message">
      信息更新成功！
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { getProfile, updateProfile, uploadAvatar, updateAvatarUrl } from '@/api/profile'
import { useAuthStore } from '@/stores/authStore'
import { ElMessage } from 'element-plus'
import { User } from '@element-plus/icons-vue'

const authStore = useAuthStore()

// 1. 用 Pinia 的 user 作为主数据源
const user = computed(() => authStore.user)

// 2. userInfo 用于表单编辑，初始值为 user
const userInfo = ref(user.value ? { ...user.value } : {})
const editInfo = ref(user.value ? { ...user.value } : {})

// 3. 监听 user 变化，自动同步 userInfo
watch(user, (newUser) => {
  if (newUser) {
    userInfo.value = { ...newUser }
    editInfo.value = { ...newUser }
  }
}, { immediate: true })

// 4. 页面挂载时拉取后端最新信息（可选，防止本地数据过期）
onMounted(async () => {
  if (user.value?.id) {
    const res = await getProfile(user.value.id)
    if (res.code === 200) { // 这里要改成 200
      authStore.setUser(res.data)
    }
  }
})

// 5. 编辑、保存逻辑不变，保存后同步 Pinia
const editing = ref(false)
const showSuccessMessage = ref(false)

// 表单验证
const emailError = computed(() => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(editInfo.value.email)) {
    return '请输入有效的邮箱地址'
  }
  return ''
})

const phoneError = computed(() => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (editInfo.value.phone && !phoneRegex.test(editInfo.value.phone)) {
    return '请输入有效的手机号码（11位数字）'
  }
  return ''
})

const isFormValid = computed(() => {
  return !emailError.value && !phoneError.value
})

const startEditing = () => {
  editInfo.value = { ...userInfo.value }
  editing.value = true
}

const cancelEditing = () => {
  editing.value = false
  emailError.value = ''
  phoneError.value = ''
}

const saveInfo = async () => {
  if (!isFormValid.value) return
  try {
    const submitData = {
      nickname: editInfo.value.nickname,
      email: editInfo.value.email,
      phone: editInfo.value.phone,
      description: editInfo.value.description
    }
    const res = await updateProfile(user.value.id, submitData)
    if (res.code === 200 && res.data) {
      editing.value = false
      ElMessage.success('个人信息更新成功')
      // 重新拉取个人中心最新数据
      const profileRes = await getProfile(user.value.id)
      if (profileRes.code === 200 && profileRes.data) { // 这里也要改成 200
        authStore.setUser(profileRes.data)
      }
    } else {
      ElMessage.error(res.message || '信息更新失败')
    }
  } catch (e) {
    ElMessage.error('信息更新失败', e)
  }
}

const showAvatarModal = ref(false)
const newAvatar = ref(null)
const uploading = ref(false)
const uploadRef = ref(null)
const newAvatarPreview = ref(null)


// 头像URL处理函数
const getAvatarUrl = (avatarPath) => {
  if (!avatarPath) return '/default-avatar.png'
  if (avatarPath.startsWith('http://') || avatarPath.startsWith('https://')) return avatarPath
  if (avatarPath.startsWith('/uploads/')) return avatarPath
  return '/default-avatar.png'
}

// 处理头像选择
const handleAvatarChange = (file) => {
  const rawFile = file.raw
  if (rawFile) {
    // 验证文件类型
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(rawFile.type)) {
      ElMessage.error('只支持 JPG、PNG、GIF 格式的图片')
      return
    }

    // 验证文件大小 (2MB)
    if (rawFile.size > 2 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过 2MB')
      return
    }

    newAvatar.value = rawFile
    newAvatarPreview.value = URL.createObjectURL(rawFile)
  }
}

// 取消头像修改
const cancelAvatarChange = () => {
  showAvatarModal.value = false
  newAvatar.value = null
  newAvatarPreview.value = null
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

// 上传头像
const handleUploadAvatar = async () => {
  if (!newAvatar.value || !user.value?.id) return
  uploading.value = true
  try {
    const uploadRes = await uploadAvatar(newAvatar.value, user.value.id)
    if (uploadRes.code === 200) {
      const avatarUrl = uploadRes.data
      const updateRes = await updateAvatarUrl(user.value.id, avatarUrl)
      if (updateRes.code === 200) {
        ElMessage.success('头像上传成功')
        const profileRes = await getProfile(user.value.id)
        if (profileRes.code === 200 && profileRes.data) {
          authStore.setUser(profileRes.data)
        }
        showAvatarModal.value = false
        newAvatar.value = null
        newAvatarPreview.value = null
        showSuccessMessage.value = true
        setTimeout(() => { showSuccessMessage.value = false }, 3000)
      } else {
        ElMessage.error(updateRes.message || '头像更新失败')
      }
    } else {
      ElMessage.error(uploadRes.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传错误:', error)
    ElMessage.error('头像上传失败，请重试')
  } finally {
    uploading.value = false
  }
}
</script>


<style scoped>
.user-profile {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.avatar-section {
  margin-bottom: 30px;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 10px;
  border: 2px solid #eee;
}

.change-avatar-btn {
  background: none;
  border: none;
  color: #2093a2;
  cursor: pointer;
  padding: 5px 10px;
}

.info-section {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
  font-size: 20px;
}

.info-form {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
}

.info-item {
  display: grid;
  grid-template-columns: 100px 1fr;
  align-items: center;
}

.info-item label {
  font-weight: 500;
  color: #666;
}

.info-value {
  padding: 8px 0;
}

input,
textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 100%;
  max-width: 400px;
}

textarea {
  min-height: 80px;
  resize: vertical;
}

.error-message {
  color: #f5222d;
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

.action-buttons {
  grid-column: 1 / -1;
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

button {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
}

.edit-btn {
  background-color: #1890ff;
  color: white;
}

.save-btn {
  background-color: #52c41a;
  color: white;
}

.save-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.cancel-btn {
  background-color: #fff;
  border: 1px solid #ddd;
  color: #666;
}

/* 头像模态框样式 */
.avatar-modal-content {
  padding: 20px 0;
}

.avatar-comparison-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.current-avatar-section,
.new-avatar-section {
  flex: 1;
  margin-bottom: 0;
}

.select-button-section {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
}

.current-avatar-section h4,
.new-avatar-section h4 {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
  font-weight: 600;
  text-align: center;
}

.current-avatar-container,
.new-avatar-container,
.placeholder-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 2px dashed #e1e5e9;
  border-radius: 8px;
  background-color: #fafafa;
  height: 180px;
  justify-content: center;
}

.preview-container,
.placeholder-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.avatar-tip,
.preview-tip,
.placeholder-tip {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
  text-align: center;
}

.file-upload-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  border: 2px dashed #e1e5e9;
  border-radius: 8px;
  background-color: #fafafa;
  min-height: 180px;
  align-items: center;
}

.avatar-upload {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  color: #666;
  font-size: 12px;
  line-height: 1.4;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 400px;
  max-width: 90%;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.success-message {
  position: fixed;
  top: 20px;
  right: 20px;
  background-color: #52c41a;
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  animation: fadeInOut 3s ease-in-out;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translateY(-20px);
  }

  10% {
    opacity: 1;
    transform: translateY(0);
  }

  90% {
    opacity: 1;
    transform: translateY(0);
  }

  100% {
    opacity: 0;
    transform: translateY(-20px);
  }
}
</style>
